﻿using AutoMapper;
using EFEntity;
using ISerives;
using Microsoft.EntityFrameworkCore;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Serives
{
    public class powersServices : IpowersServices
    {
        private readonly MyDbContext myDbContext;
        private readonly IMapper mapper;
        public powersServices(MyDbContext myDbContext, IMapper mapper)
        {
            this.myDbContext = myDbContext;
            this.mapper = mapper;
        }

        public async Task<int> Del(int sid)
        {
            
             int num =await myDbContext.Epower.FromSqlRaw($@"DELETE FROM QuanXian  WHERE QName={sid}").CountAsync();
           
            return num;
        }

        public async Task<List<power>> Select(int ids, string id)
        {
            List<power> list = new List<power>();
            List<Epower> list2 = new List<Epower>();
            if (id == null)
            {
                await Task.Run(() =>
                {
                    list2 = myDbContext.Epower.FromSqlRaw($@"select q.id, q.text, q.state,q.pid,q.qurl,qr.QName,
                             case
                             when qr.QName is null then 0
                             else 1
                            end as checked
                            from power q
                            left join(select QName from dbo.QuanXian where Role={ids}) qr on q.id=qr.QName
                            where q.pid=0").ToList();
                });

            }
            else
            {
                await Task.Run(() =>
                {
                    list2 = myDbContext.Epower.FromSqlRaw($@"select q.id, q.text, q.state,q.pid,q.qurl,qr.QName,
                             case
                             when qr.QName is null then 0
                             else 1
                            end as checked
                            from power q
                            left join(select QName from dbo.QuanXian where Role={ids}) qr on q.id=qr.QName
                            where q.pid={id}").ToList();
                });
            }
            list = mapper.Map<List<power>>(list2);

            return list;
        }
    }
}
